package com.x.example.demo;

import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.x.uikit.page.XPage;
import com.x.uikit.page.XPageManager;


public class WebPage extends XPage {
    private WebView mWebView;
    private LinearLayout mContainer;
    private TextView mTvTitle;

    public WebPage(@NonNull Context context) {
        super(context);

    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContainer = new LinearLayout(getContext());
        this.addView(mContainer, -1, -1);
        mContainer.setOrientation(LinearLayout.VERTICAL);
        mTvTitle = new TextView(getContext());
        mTvTitle.setTextColor(0xff333333);
        mTvTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
        mTvTitle.setGravity(Gravity.CENTER);
        mContainer.addView(mTvTitle, -1, -2);
        View divider = new View(getContext());
        divider.setBackgroundColor(0xff999999);
        mContainer.addView(divider, -1, 1);

        mWebView = new WebView(getContext());
        mContainer.addView(mWebView, -1, -1);
        mWebView.setWebViewClient(new WebViewClient() {
            //设置在webView点击打开的新网页在当前界面显示,而不跳转到新的浏览器中
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                mTvTitle.setText(title);
            }
        });
        mWebView.getSettings().setJavaScriptEnabled(true);  //设置WebView属性,运行执行js脚本


        String url = getArgument().getString("url", "https://www.baidu.com/");
        mWebView.loadUrl(url);          //调用loadUrl方法为WebView加入链接
    }

    @Override
    public boolean onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        } else {
            XPageManager manager = XPageManager.of(getContext());
            if (manager != null) {
                return super.onBackPressed();
            }
            return false;
        }
    }
}
